<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'

import {
  getDepartmentListApi,
  getManagerListApi,
  delDepartmentApi,
  addDepartmentApi,
  editDepartmentApi,
  getDepartmentDetailApi
} from '@/api/departments'

import type { TreeData, ManagerList, OpearteType, OperateForm } from '@/types/departments'

import { getTreeData } from '@/utils/filter-tree'

import { delConfim, requestMessage } from '@/utils/del-confim'

import { ArrowDown } from '@element-plus/icons-vue'
import type { ElForm } from 'element-plus'

const active = 'first'

const configProps = {
  label: 'name'
}

const operateFormRef = ref<null | InstanceType<typeof ElForm>>(null)

const treeList = ref<TreeData>([])

const showOpearte = ref(false)

const operateId = ref('')

const opearteType = ref<OpearteType>('add')

const operateFormData = ref<OperateForm>({
  pid: '',
  name: '',
  code: '',
  manager: '',
  introduce: ''
})

const operateTitle = computed(() => {
  let operateTitle = '添加'
  if (opearteType.value === 'add') {
    operateTitle = '添加'
  }
  if (opearteType.value === 'view') {
    operateTitle = '编辑'
  }
  return operateTitle + '部门'
})

const managerList = ref<ManagerList>([])

async function getTreeList(): Promise<undefined> {
  const { data } = await getDepartmentListApi()
  treeList.value = getTreeData(data)
}

async function getManagerList(): Promise<undefined> {
  const { data } = await getManagerListApi()
  managerList.value = data
}

async function getDepartmentDetail() {
  const { data } = await getDepartmentDetailApi(operateId.value)
  console.log(data)

  const { id, pid, name, code, manager, introduce, createTime } = data
  operateFormData.value = { id, pid, name, code, manager, introduce, createTime }
}

function delDepartment() {
  delConfim(async () => {
    if (!operateId.value) return false
    try {
      const res = await delDepartmentApi(operateId.value)
      console.log(res.data)
      return true
    } catch (error) {
      return false
    }
  })
}

async function operateDepartment() {
  if (opearteType.value === 'add') {
    await addDepartment()
  } else {
    await editDepartment()
  }
  getTreeList()
}

async function addDepartment() {
  operateFormData.value.pid = operateId.value
  await requestMessage('添加', async () => {
    try {
      const { success } = await addDepartmentApi(operateFormData.value)
      return success
    } catch (err) {
      return false
    }
  })
}

async function editDepartment() {
  await requestMessage('修改', async () => {
    try {
      const { success } = await editDepartmentApi(operateId.value, operateFormData.value)
      return success
    } catch (err) {
      return false
    }
  })
}

onMounted(() => {
  getTreeList()
  getManagerList()
})

async function onSelectOperate(e: OpearteType, id: string) {
  operateId.value = id
  opearteType.value = e
  if (e === 'view') {
    await getDepartmentDetail()
  }
  if (e === 'del') {
    delDepartment()
  } else {
    showOpearte.value = true
  }
}

function onClearDatas(close: () => void) {
  operateFormData.value = {
    pid: '',
    name: '',
    code: '',
    manager: '',
    introduce: ''
  }
  close()
}

function onCancel() {
  operateId.value = ''
  opearteType.value = 'add'
  showOpearte.value = false
}

async function onSubmit() {
  await operateDepartment()
  onCancel()
}
</script>

<template>
  <div class="department-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-tabs v-model="active" class="demo-tabs">
            <el-tab-pane label="组织架构" name="first" />
          </el-tabs>
        </div>
      </template>

      <div class="scroll-box">
        <el-tree
          :data="treeList"
          node-key="id"
          :render-after-expand="false"
          :expand-on-click-node="false"
          :props="configProps"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <div class="label">
                {{ node.label }}
              </div>
              <div class="opearte">
                <el-button link>{{ data.manager }}</el-button>
                <el-dropdown @command="($event:OpearteType)=>onSelectOperate($event,data.id)">
                  <span class="el-dropdown-link">
                    操作
                    <el-icon><ArrowDown /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                      <el-dropdown-item command="view" v-if="data.id">查看部门</el-dropdown-item>
                      <el-dropdown-item command="del" v-if="data.id">删除部门</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
        </el-tree>
      </div>
    </el-card>

    <el-dialog v-model.sync="showOpearte" :title="operateTitle" :before-close="onClearDatas">
      <el-form ref="operateFormRef" :model="operateFormData" label-width="120">
        <el-form-item label="部门名称">
          <el-input v-model="operateFormData.name" />
        </el-form-item>

        <el-form-item label="部门编码">
          <el-input v-model="operateFormData.code" />
        </el-form-item>

        <el-form-item label="部门负责人">
          <el-select v-model="operateFormData.manager" placeholder="please select your zone">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="部门介绍">
          <el-input v-model="operateFormData.introduce" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.department-page {
  box-sizing: border-box;
  padding: 20px;
  height: 100%;
  :deep(.el-card) {
    padding: 20px;
    height: 100%;
    .el-card__header,
    .el-card__body {
      margin-left: 20px;
    }
    .el-card__header {
      padding: 20px 0 0 20px;
      border-bottom: 0 none;
    }
    .el-card__body {
      padding: 10px 120px;
      height: calc(100% - 60px);
      .scroll-box {
        height: 100%;
        overflow: auto;
        padding: 20px 0;
        .el-tree {
          .el-tree-node {
            .el-tree-node__content {
              height: 36px;
              .custom-tree-node {
                height: 36px;
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                .opearte {
                  display: flex;
                  align-items: center;
                  .el-button {
                    padding-right: 30px;
                    margin: 0;
                  }

                  .el-dropdown {
                    height: 100%;
                    display: flex;
                    align-items: center;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  :deep(.el-dialog) {
    .el-dialog__header {
      margin-right: 0;
    }
    .el-dialog__body {
      .el-form {
        .el-form-item {
          .el-form-item__content {
            .el-select {
              width: 100%;
            }
          }
        }
      }
    }
  }
}
</style>
